package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.pojo.*;
import com.itheima.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Override
    public void submitOrer(Orders orders) {

        Long userId = BaseContext.get();
        //查询用户的购物车  list<ShoppingCart>
        List<ShoppingCart> shoppingCartList = shoppingCartService.lambdaQuery().eq(ShoppingCart::getUserId, userId).list();
        //查询用户信息 User
        User user = userService.getById(userId);

        //查询用户地址信息 AddressBook
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        //生成订单ID
        long orderId = IdWorker.getId();//雪花算法生成的Id
        BigDecimal total=new BigDecimal(0);

        //2.添加订单详情数据，操作的是order-detail表（多条数据）
        List<OrderDetail> orderDetailList=new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);//订单id
            orderDetail.setNumber(cart.getNumber());//设置数量
            orderDetail.setDishFlavor(cart.getDishFlavor());//口味
            orderDetail.setDishId(cart.getDishId());//菜品id
            orderDetail.setSetmealId(cart.getSetmealId());//套餐id
            orderDetail.setName(cart.getName());//名称
            orderDetail.setImage(cart.getImage());//图片
            orderDetail.setAmount(cart.getAmount());//金额 单价

            BigDecimal multiply = orderDetail.getAmount().multiply(new BigDecimal(orderDetail.getNumber()));

            total=total.add(multiply);
            orderDetailList.add(orderDetail);
        }
        orderDetailService.saveBatch(orderDetailList);

        //1.添加订单数据，操作orders表（一条数据）
        orders.setOrderTime(LocalDateTime.now());//下单时间
        orders.setCheckoutTime(LocalDateTime.now());//支付时间
        orders.setStatus(2);//状态 订单状态 1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setUserId(userId);//用户id
        orders.setNumber(String.valueOf(orderId));//订单编号
        orders.setId(orderId);
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());//收获人
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setAmount(total);// 总金额

        this.save(orders);



        //清空购物车数据
        shoppingCartService.lambdaUpdate().eq(ShoppingCart::getUserId, userId).remove();




    }


    /**
     * 查询所有订单
     * @param page
     * @param pageSize
     * @return
     */

    @Autowired
    OrdersMapper ordersMapper;
    @Override
    public Page<OrdersDto> getOrdersDtoPage(Integer page, Integer pageSize, Long userId) {
        Page<OrdersDto> pageInto = new Page<>(page, pageSize);
        return ordersMapper.getOrdersDtoPage(pageInto,userId);
    }


    @Override
    public void getshopping(Orders orders) {
        //生成订单ID
        long orderId = IdWorker.getId();//雪花算法生成的Id
        List<ShoppingCart> shoppingCartList=new ArrayList<>();
        List<OrderDetail> list = orderDetailService.lambdaQuery()
                .eq(OrderDetail::getOrderId, orders.getId())
                .list();
        Long userId = BaseContext.get();
        //查询用户信息 User
        User user = userService.getById(userId);
        for (OrderDetail orderDetail : list) {

            ShoppingCart shoppingCart=new ShoppingCart();
            shoppingCart.setUserId(userId);
            shoppingCart.setNumber(orderDetail.getNumber());//设置数量
            shoppingCart.setDishFlavor(orderDetail.getDishFlavor());//口味
            shoppingCart.setDishId(orderDetail.getDishId());//菜品id
            shoppingCart.setSetmealId(orderDetail.getSetmealId());//套餐id
            shoppingCart.setName(orderDetail.getName());//名称
            shoppingCart.setImage(orderDetail.getImage());//图片
            shoppingCart.setAmount(orderDetail.getAmount());//金额 单价

            shoppingCartList.add(shoppingCart);
        }

        shoppingCartService.saveBatch(shoppingCartList);
    }
}
